package com.zp.server;

import com.zp.server.server.ZpServer;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author zhangpeng
 * @version 1.0.0
 * @date 2019/6/22 13:05
 * @since 1.0
 */
@SpringBootApplication
@Log4j2
public class NettyServerApplication  implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(NettyServerApplication.class);
    }

    @Autowired
    private ZpServer zpServer;

    /**
     * 是否启动完成
     */
    private AtomicBoolean started =new AtomicBoolean(false);

    /**
     * 关闭
     */
    private AtomicBoolean stoped =new AtomicBoolean(false);


    @Override
    public void run(String... args) throws Exception {
        if(started.compareAndSet(false,true)) {
            log.info("start");
            zpServer.start();
        }else {
            log.warn("重复执行start");
        }

        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                if(stoped.compareAndSet(false,true)){
                    log.info("stop");
                    zpServer.stop();
                }else{
                    log.warn("重复执行stop");
                }
            }
        });
    }
}
